#include "MySQLConn.h"

MySQLConn::MySQLConn() :m_conn(nullptr), m_result(nullptr), m_row(nullptr)
{
	m_conn = mysql_init(nullptr);
	mysql_set_character_set(m_conn, "utf8");
}

MySQLConn::~MySQLConn()
{
	if (m_conn)
		mysql_close(m_conn);
	freeResult();
}

bool MySQLConn::connect(std::string user, std::string passwd, std::string dbName, std::string ip, unsigned short port)
{
	MYSQL* ptr = mysql_real_connect(m_conn, ip.c_str(), user.c_str(), passwd.c_str(), dbName.c_str(), port, nullptr, 0);
	return ptr != nullptr;
}

bool MySQLConn::update(std::string sql)
{
	if (mysql_query(m_conn, sql.c_str()));
	{
		return false;
	}
	return true;
}

bool MySQLConn::query(std::string sql)
{
	freeResult();
	if (mysql_query(m_conn, sql.c_str()));
	{
		return false;
	}
	m_result = mysql_store_result(m_conn);
	return true;
}

bool MySQLConn::next()
{
	if (m_result != nullptr)
	{
		m_row = mysql_fetch_row(m_result);
	}
	return false;
}

std::string MySQLConn::value(int index)
{
	int count = mysql_num_fields(m_result);
	if (index >= count || index < 0)
	{
		return std::string();
	}
	const char* val = m_row[index];
	size_t len = mysql_fetch_lengths(m_result)[index];
	return std::string(val, len);
}

bool MySQLConn::transaction()
{
	return mysql_autocommit(m_conn, false);
}

bool MySQLConn::commit()
{
	return mysql_commit(m_conn);
}

bool MySQLConn::rollback()
{
	return mysql_rollback(m_conn);
}

void MySQLConn::freeResult()
{
	if (m_result) {
		mysql_free_result(m_result);
	}
}
